import { forwardRef, ButtonHTMLAttributes, ReactNode } from 'react';
import { clsx } from 'clsx';
import { Loader2 } from 'lucide-react';

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'ghost' | 'danger';
  size?: 'sm' | 'md' | 'lg';
  loading?: boolean;
  icon?: ReactNode;
  iconPosition?: 'left' | 'right';
  fullWidth?: boolean;
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      children,
      variant = 'primary',
      size = 'md',
      loading = false,
      icon,
      iconPosition = 'left',
      fullWidth = false,
      disabled,
      className,
      ...props
    },
    ref
  ) => {
    const baseClasses = [
      'inline-flex items-center justify-center gap-2',
      'border rounded-lg font-medium',
      'transition-all duration-200',
      'focus:outline-none focus:ring-2 focus:ring-offset-2',
      'disabled:opacity-50 disabled:cursor-not-allowed',
    ];

    const variantClasses = {
      primary: [
        'bg-primary-600 text-white border-transparent',
        'hover:bg-primary-700 active:bg-primary-800',
        'focus:ring-primary-500',
      ],
      secondary: [
        'bg-white text-gray-900 border-gray-300',
        'hover:bg-gray-50 active:bg-gray-100',
        'focus:ring-primary-500',
      ],
      ghost: [
        'bg-transparent text-gray-700 border-transparent',
        'hover:bg-gray-100 active:bg-gray-200',
        'focus:ring-primary-500',
      ],
      danger: [
        'bg-red-600 text-white border-transparent',
        'hover:bg-red-700 active:bg-red-800',
        'focus:ring-red-500',
      ],
    };

    const sizeClasses = {
      sm: 'px-3 py-1.5 text-sm h-8',
      md: 'px-4 py-2 text-sm h-10',
      lg: 'px-6 py-3 text-base h-12',
    };

    const widthClasses = fullWidth ? 'w-full' : '';

    const isDisabled = disabled || loading;

    const iconElement = loading ? <Loader2 className='w-4 h-4 animate-spin' /> : icon;

    return (
      <button
        ref={ref}
        disabled={isDisabled}
        className={clsx(
          baseClasses,
          variantClasses[variant],
          sizeClasses[size],
          widthClasses,
          className
        )}
        {...props}
      >
        {iconElement && iconPosition === 'left' && iconElement}
        {children}
        {iconElement && iconPosition === 'right' && iconElement}
      </button>
    );
  }
);

Button.displayName = 'Button';

export default Button;
